package com.hiquety.tcb;

import com.hiquety.tcb.config.AppInfo;
import com.hiquety.tcb.config.ClipboardSystem;
import com.hiquety.tcb.disk.ClipboardItemDisk;
import com.hiquety.tcb.entity.ClipboardItem;
import com.hiquety.tcb.listener.AboutBtnClickListener;
import com.hiquety.tcb.listener.CenterBtnClickListener;
import com.hiquety.tcb.listener.ClipboardListener;
import com.hiquety.tcb.listener.ShowBtnClickListener;
import com.hiquety.tcb.task.ClipboardTask;
import com.hiquety.tcb.ui.IndexUI;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

public class App extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        initOldData();
        initClipboardTask();
        initSystemTray();
    }

    private void initSystemTray() throws IOException, AWTException {
        Platform.setImplicitExit(false);
        BufferedImage image = ImageIO.read(App.class.getResourceAsStream(AppInfo.ICON_PATH));

        PopupMenu popupMenu = new PopupMenu();
        java.awt.MenuItem menuItem1 = new java.awt.MenuItem("剪切板");
        java.awt.MenuItem menuItem3 = new java.awt.MenuItem("统计");
        java.awt.MenuItem menuItem2 = new java.awt.MenuItem("关于");
        popupMenu.add(menuItem1);
        popupMenu.add(menuItem3);
        popupMenu.add(menuItem2);
        menuItem1.addActionListener(new ShowBtnClickListener());
        menuItem3.addActionListener(new CenterBtnClickListener());
        menuItem2.addActionListener(new AboutBtnClickListener());

        MenuShortcut aa=new MenuShortcut(KeyEvent.KEY_FIRST);
        menuItem1.setShortcut(aa);
        TrayIcon trayIcon = new TrayIcon(image, AppInfo.TITLE, popupMenu);

        SystemTray systemTray = SystemTray.getSystemTray();
        systemTray.add(trayIcon);
    }

    private void initOldData() {
    List<ClipboardItem> read = ClipboardItemDisk.read();
        if (read != null) {
            for (ClipboardItem clipboardItem : read) {
                IndexUI.observableList.add(clipboardItem);
                ClipboardSystem.ai.put(clipboardItem.getMd5(), clipboardItem);
            }
        }
    }

    private void initClipboardTask() {
        ClipboardTask clipBoardTask = new ClipboardTask();
        Thread thread = new Thread(clipBoardTask);
        thread.start();
        clipBoardTask.messageProperty().addListener(new ClipboardListener());
    }
}
